﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace WebChatClient.Controllers
{
    public class LogOutController : Controller
    {
        HttpClient client = new HttpClient();
        List<Chatter> ListChatter;
        //
        // GET: /LogOut/

        public LogOutController()
        {
            client.BaseAddress = new Uri("http://localhost:63046/");
            client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));

            ListChatter = new List<Chatter>();
        }

        public ActionResult Index()
        {
            Chatter Me = GetCurrentChatterModel();
            Me.Status = 0;

            HttpResponseMessage  response = client.PutAsJsonAsync("api/ChatterAPI/"+ Me.Id, Me).Result;
            if (response.IsSuccessStatusCode)
            {
                
            }
            FormsAuthentication.SignOut();
            return View();
        }

        private Chatter GetCurrentChatterModel()
        {
            Chatter tempchatter = new Chatter();
            string CurrentUserNick = User.Identity.Name;


            // Get the chatter list from the server
            HttpResponseMessage response = client.GetAsync("api/ChatterAPI").Result;  // Blocking call!
            if (response.IsSuccessStatusCode)
            {
                // Parse the response body. Blocking!
                var products = response.Content.ReadAsAsync<IEnumerable<Chatter>>().Result;
                foreach (var p in products)
                {
                    ListChatter.Add(p);
                }
            }

            //Compare the name to get right model

            for (int i = 0; i < ListChatter.Count; i++)
            {
                if (ListChatter[i].Nick == CurrentUserNick)
                    tempchatter = ListChatter[i];
            }
            return tempchatter;
        }

    }
}
